package com.qkl.upload.publics.web.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.qkl.upload.publics.utils.CommonCryptoUtils;
import com.qkl.upload.publics.utils.ErrorCodeUtils;
import com.qkl.upload.publics.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public  class AppInterceptor implements HandlerInterceptor {

    private ObjectMapper objectMapper = new ObjectMapper();

    private static List<String> URL_CHECK_TOKEN = new ArrayList<>();
    static {
        URL_CHECK_TOKEN.add("/uploadFile");
    }
    private static boolean isCheckToken(String url){
        for (String checkUrl : URL_CHECK_TOKEN){
            if(url.endsWith(checkUrl)){
                return true;
            }
        }
        return false;
    }

    private static boolean isCheckSign(String url){
        return !isCheckToken(url);
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        String sign = StringUtils.trimToEmpty(request.getHeader("sign"));
        String token = StringUtils.trimToEmpty(request.getHeader("token"));
        if(StringUtils.isEmpty(sign)){
            sign = StringUtils.trimToEmpty(request.getParameter("sign"));
        }
        log.info("===preHandle.uri={},sign={},token={}",uri,sign,token);
        Result result = null;
        if(StringUtils.isAllEmpty(sign,token)){
            result = Result.error(ErrorCodeUtils.SIGN_EMPTY,ErrorCodeUtils.SIGN_EMPTY_MSG);
        }else if(isCheckSign(uri)){
            if(StringUtils.isEmpty(sign)){
                result = Result.error(ErrorCodeUtils.SIGN_EMPTY,ErrorCodeUtils.SIGN_EMPTY_MSG);
            }else {
                CommonCryptoUtils.UploadCrypto crypto = CommonCryptoUtils.decryptUpload(sign);
                log.info("===preHandle.decrypt crypto={}}", crypto);
                if (null == crypto) {
                    result = Result.error(ErrorCodeUtils.SIGN_INVALID, ErrorCodeUtils.SIGN_INVALID_MSG);
                } else if (crypto.timeout()) {
                    result = Result.error(ErrorCodeUtils.SIGN_EXPIRE, ErrorCodeUtils.SIGN_EXPIRE_MSG);
                }
            }
        }

        if(null != result){
            response.reset();
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(objectMapper.writeValueAsString(result));
            response.getWriter().close();
            return false;
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }


}
